package com.leagueautoattack.main;

import com.leagueautoattack.util.OCRUtil;
import com.leagueautoattack.util.Utils;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.User32;
import net.sourceforge.tess4j.TesseractException;

import java.awt.*;
import java.awt.image.BufferedImage;

import static java.awt.event.KeyEvent.VK_SPACE;

public class Run {

    private static Robot robot;

    private static float attackSpeed;

    static {

        System.setProperty("sun.java2d.uiScale", "1");

        try {
            robot = new Robot();
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) throws InterruptedException {

        Native.isProtected();

        var config = Utils.readConfig();

        Thread thread = new Thread(() -> {

            while (true) {

                BufferedImage img = robot.createScreenCapture(config.rectangle());

                try {
                    attackSpeed = OCRUtil.getAttackSpeed(img);
                } catch (TesseractException e) {
                    throw new RuntimeException(e);
                }

            }

        });

        thread.start();

        while (true) {

            if(User32.INSTANCE.GetAsyncKeyState(VK_SPACE) != 0) {

                if(attackSpeed > 0) {

                    Utils.KeyboardKeyDown(config.autoAttackKey());
                    Thread.sleep(10);
                    Utils.KeyboardKeyUp(config.autoAttackKey());
                    Thread.sleep((int)((1000 / attackSpeed) * config.preAttack()));

                    Utils.MouseRightButtonDown();
                    Thread.sleep(10);
                    Utils.MouseRightButtonUp();
                    Thread.sleep((int)((1000 / attackSpeed) * config.postAttack()));

                }

            }

        }

    }

}
